<template>
  <div
    style="
      vertical-align: middle;
      background-color: rgb(248, 248, 248);
      padding: 10px 0;
    "
  >
    <div class="create-order">
      <form id="orderForm" method="post">
        <div id="receiver" class="create-order-receiver panel">
          <div class="panel-heading">
            <h5>收货地址</h5>
          </div>
          <div class="panel-body" style="">
            <a class="add-receiver" href="#">
              <i class="el-icon-plus" style="color: #999"></i>
              添加收货地址
            </a>
            <ul class="receiver-list">
              <li :class="isActive == true ? 'addressActive' : null" @click="changeValue(add.id)" v-for="add in addresses" :key="add.id">
                <h5 class="text-overflow" :title="add.consignee">{{ add.consignee }}</h5>
                <p class="text-gray-dark">{{add.phone}}</p>
                <p class="text-overflow" :title="add.areaName + add.address">
                  {{ add.areaName }}&nbsp;{{ add.address }}
                </p>
                <p class="text-gray-dark">{{ add.zipCode }}</p>
              </li>
            </ul>
          </div>
        </div>
        <div id="paymentMethod" class="create-order-payment panel">
          <div class="panel-heading">
            <h5>支付方式</h5>
          </div>
          <div class="panel-body">
            <ul class="payment-list">
              <li class="list-li-light" style="border-color: #49a9ee" :value="createOrder.paymentMethodName">
                网上支付
              </li>
            </ul>
          </div>
        </div>
        <div id="shippingMethod" class="create-order-shipping panel">
          <div class="panel-heading">
            <h5>配送方式</h5>
          </div>
          <div class="panel-body">
            <ul class="shipping-list open">
              <li class="list-li-light" style="border-color: #49a9ee">
                普通物流
              </li>
            </ul>
          </div>
        </div>
        <div class="panel">
          <div class="panel-body">
            <div class="form-group el-row">
              <label class="el-col-2 control-label">备注</label>
              <div class="el-col-8">
                <input
                  name="note"
                  class="control-input"
                  type="text"
                  maxlength="200"
                  placeholder="买家留言"
                  v-model="orderInfo.memo"
                />
              </div>
            </div>
          </div>
        </div>
        <div class="panel">
          <table style="width: 100%; background-color: white">
            <!-- 抬头 -->
            <thead>
              <tr>
                <th width="800px">商品</th>
                <th>价格</th>
                <th>数量</th>
                <th width="150px">小计</th>
              </tr>
            </thead>
            <!-- 内容 -->
            <tbody class="cart-items" v-for="product in shop" :key="product.id">
              <!-- 店铺名 -->
<!--              <tr class="cart-items-heading">
                <td>
                  <p>店铺名</p>
                </td>
              </tr>-->
              <!-- 商品 -->
              <tr class="cart-items-body">
                <td>
                  <div class="items-body-information">
                    <div class="information-left">
                      <img
                        class="information-image"
                        :src="shopping[product.id].attributeValue0"
                        :alt="product.name"
                      />
                    </div>
                    <div class="information-body">
                      <h5>{{product.name}}</h5>
                    </div>
                  </div>
                </td>
                <td>￥ {{ product.cost }}</td>
                <td class="items-body-number">
                  <div class="number">
                    <span class="number-control">{{product.quantity}}</span>
                  </div>
                </td>
                <td>
                  <strong class="subtotal">￥{{product.cost * product.quantity}}</strong>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="create-order-summary panel">
          <div class="panel-body">
            <dl class="body-pull-right">
              <dt>促销折扣:</dt>
              <dd>
                <span id="promotionDiscount">￥0. 00元</span>
              </dd>
              <dt>优惠券折扣:</dt>
              <dd>
                <span id="couponDiscount">￥0. 00元</span>
              </dd>
              <dt>运费:</dt>
              <dd>
                <span id="freight">￥{{ orderInfo.freight }}. 00元</span>
              </dd>
            </dl>
          </div>
        </div>
        <div class="panel">
          <div class="combined">
            <div class="el-row">
              <div class="el-col-2">
                <a class="combined-back" href="#">返回</a>
              </div>
              <div class="el-col-20 text-right">
                <span style="margin-right: 20px">
                  应付金额:
                  <strong class="combined-sum">￥{{orderInfo.amount}}元</strong>
                </span>
              </div>
              <div class="el-col-2">
                <button class="combined-btn" @click.prevent="dialogVisible = true,getTime(),createOrder(orderInfo,$event)">
                  订单结算
                </button>
              </div>
              <el-dialog
                title="支付二维码"
                v-model="dialogVisible"
                width="30%"
                :before-close="handleClose"
              >
                <img src="@/assets/image/二维码.png" alt="">
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="dialogVisible = false,gotoPay(payInfo,$event)">确 定</el-button>
                  </span>
                </template>
              </el-dialog>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import router from "@/router";
import { ElMessage } from 'element-plus';
import {ref, toRaw} from "vue";
import {showaddress} from "@/api/address";
import {createorder} from "@/api/shoppingcart";
import { useStore } from 'vuex';
import {getproductInfo} from "@/api/shoppingcart";
import {pay} from "@/api/shoppingcart";

export default {
  name: "createOrder",
  setup() {
    let store =useStore()
    let shop = toRaw(store.state.shop)  //商品信息
    console.log(shop);
    let shopping = ref([])  //详细商品信息
    let addresses = ref({});   //地址信息
    let date = null;   //当前时间
    let orderInfo = ref({   //创建订单的请求参数
      memberId:localStorage.getItem('id'),
      consignee:'',
      address:'',
      areaName:'',
      phone:'',
      zipCode:'',
      paymentMethodName:'网上支付',
      shippingMethodName:'普通物流',
      memo:'',     //备注
      storeId:'',   //店铺
      createdDate:'',  //创建日期
      price:[],   //价格
      quantity:[],   //数量
      freight:8,    //运费
      amount:0,   //订单金额
      status:0,   //订单状态
      skuId:[],   //商品
    });
    let isActive = ref(false)  //判断是否有选择地址
    let payInfo = ref({
      orderId:'',
      productName:'兰蔻 专业造型眉刷',
      price:408,
    })

    // 获取全部地址
    function getAddress(){
      showaddress().then((res) => {
        addresses.value = res.data.data;
      });
    }
    getAddress()
    console.log("addresses",addresses)

    // 获取购买商品图片
    function getProductImg(){
      for(let i = 0;i<shop.length;i++){
        let id = shop[i].id;
        // console.log("id",id);
        getproductInfo(id).then((res) => {
          shopping.value[id] = res.data.data;
          console.log("shopping",shopping);
        })
      }
    }
    getProductImg()
    console.log("shopping",shopping);

    // 计算总价
    function getAllPrice(){
      let allPrice = ref(0);
      for(let i = 0;i<shop.length;i++){
        orderInfo.value.price[i] = shop[i].quantity * shop[i].cost;
        allPrice.value += shop[i].quantity * shop[i].cost;
        orderInfo.value.quantity[i] = shop[i].quantity;
        orderInfo.value.skuId[i] = shop[i].id;
      }
      orderInfo.value.amount = allPrice.value + orderInfo.value.freight;
    }
    getAllPrice()

    // 创建订单
    function createOrder(formName,e){
      createorder(orderInfo)
          .then((res) => {
            console.log(res);
            payInfo.value.orderId = res.data.data.orderId.c[0].toString() + res.data.data.orderId.c[1];
            console.log(payInfo);
            if (res.data.code === 401) {
              let target = e.target;
              if (target.nodeName === "SPAN") {
                target = e.target.parentNode;
              }
              target.blur();
              return;
            }
            ElMessage.success('订单创建成功')
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("订单创建失败");
          });
      router.replace('/member/address')
    }

    function getPayInfo(){
      for(let i = 0 ; i<shop.length ; i++){
        payInfo.value.productName += shop[i].name + ' ';
      }
      payInfo.value.price = orderInfo.value.amount;
      console.log("payInfo",payInfo);
    }

    //支付
    function gotoPay(payInfo,e){
      getPayInfo()
      pay(payInfo)
          .then((res) => {
            console.log(res);
            if (res.data.code === 401) {
              let target = e.target;
              if (target.nodeName === "SPAN") {
                target = e.target.parentNode;
              }
              target.blur();
              return;
            }
            ElMessage.success('支付成功')
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("支付失败");
          });
      router.replace('/')
    }

    // 获取当前时间
    function getTime(){
      date = new Date();
      let xx = date.getFullYear();
      let yy = date.getMonth();
      if(yy<10) yy = '0' + yy;
      let zz = date.getDate()
      if(zz<10) zz = '0' + zz;
      let hh = date.getHours();
      if(hh<10) hh = '0' + hh;
      let mm = date.getMinutes();
      if(mm<10) mm = '0' + mm;
      let ss = date.getSeconds();
      if(ss<10) ss = '0' + ss;
      orderInfo.value.createdDate = xx +'-'+ yy +'-'+ zz +' '+ hh +':'+ mm +':'+ ss;
      console.log(orderInfo.value);
    }

    function gohome() {
      router.replace("/home");
    }
/*    function go(){
      router.replace("/member/index");
      ElMessage.success('支付成功')
    }*/

    // 获取当前选中的地址并修改
    function changeValue(id){
      isActive.value = !isActive.value;
      for(let i=0;i<addresses.value.length;i++){
        if(addresses.value[i].id == id){
          orderInfo.value.consignee = addresses.value[i].consignee;
          orderInfo.value.address = addresses.value[i].address;
          orderInfo.value.areaName = addresses.value[i].areaName;
          orderInfo.value.phone = addresses.value[i].phone;
          orderInfo.value.zipCode = addresses.value[i].zipCode;
          console.log("orderInfo",orderInfo);
        }
      }
    }

    return {
      shop,
      shopping,
      orderInfo,
      addresses,
      isActive,
      payInfo,
      gotoPay,
      gohome,
      getTime,
      createOrder,
      changeValue,
    };
  },
  data() {
    return {
      dialogVisible: false,
    }
  },
  methods: {
    handleClose(done) {
        this.$confirm('确认关闭？')
          .then(() => {
            ElMessage.success('支付成功')
            done()
          })
          .catch(() => {})
      },
  },
};
</script>

<style scoped>
* {
  color: #333333;
  font-size: 13px;
}
a {
  text-decoration: none;
}
h5 {
  font-weight: normal;
}
ul,
li,
dl,
dd,
dt,
th,
td {
  list-style: none;
  margin: 0;
  padding: 0;
}
h5,
p {
  margin: 0;
  padding: 0;
}
li.list-li-light:hover {
  border-color: #49a9ee;
}
.text-overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.text-right {
  text-align: right;
}
.panel {
  padding: 0 15px;
  margin-bottom: 10px;
  border-radius: 0;
  border: none;
}
.create-order {
  width: 1350px;
  margin: 10px auto;
}
.panel-heading {
  padding: 10px 15px;
  border-bottom: 1px #eeeeee solid;
  background-color: #ffffff;
}
.panel-body {
  padding: 15px;
  background-color: #ffffff;
}
.add-receiver {
  width: 310px;
  height: 120px;
  line-height: 120px;
  float: left;
  color: #999999;
  font-size: 15px;
  text-align: center;
  margin-left: 6px;
  margin-right: 6px;
  transition: color 0.3s;
  /*border: 1px #999999 dashed;
  border-radius: 2px;*/
}
.receiver-list{
  display: table-cell;
  height: 100%;
  width: 100%;
}
.receiver-list li {
  width: 280px;
  height: 110px;
  float: left;
  padding: 5px 15px;
  margin-left: 6px;
  margin-right: 6px;
  margin-bottom: 1%;
  cursor: pointer;
  /* background: url(../../assets/image/order.png) 0 0 no-repeat; */
}
.addressActive {
  background-position: 0 -150px;
  background-color: #fffbf9;
}
.receiver-list li.active h5 {
  color: #49a9ee;
}
.receiver-list li h5 {
  line-height: 30px;
  margin-bottom: 5px;
  transition: color 0.3s;
  border-bottom: 1px #eeeeee dotted;
}
.receiver-list li p {
  line-height: 24px;
}
.text-gray-dark {
  color: #919191;
}
.payment-list {
  height: 50px;
}
.payment-list li {
  width: 200px;
  line-height: 30px;
  float: left;
  padding: 10px;
  margin-right: 20px;
  cursor: pointer;
  transition: border-color 0.3s;
  border: 1px #eeeeee solid;
}
.shipping-list {
  height: 50px;
}
.shipping-list li {
  width: 200px;
  line-height: 30px;
  float: left;
  padding: 10px;
  margin-right: 20px;
  cursor: pointer;
  transition: border-color 0.3s;
  border: 1px #eeeeee solid;
}
.control-label {
  text-align: right;
  color: #666 !important;
  margin-bottom: 0;
  margin-right: 10px;
  padding: 7px 10px 0;
}
.control-input {
  display: block;
  width: 100%;
  padding: 8px 12px;
  font-size: 12px;
  color: #555;
  background-color: #fff;
  border: 1px #ccc solid;
  border-radius: 4px;
}
.control-input:hover {
  border-color: #49a9ee;
  box-shadow: 0 2px 12px 0 rgba(73, 169, 238, 0.1);
}

/* 商品 */
/* 抬头 */
table thead th {
  color: #666666;
  font-weight: normal;
  text-align: left;
  padding: 10px;
  border-bottom: 10px #f8f8f8 solid;
}
/* 内容 */
.cart-items {
  border-bottom: 10px #f8f8f8 solid;
}
/* 店铺名 */
.cart-items-heading {
}
.cart-items-heading td {
  padding: 10px;
  border-bottom: 1px #eeeeee solid;
}
/* 内容 */
.cart-items-body {
}
.cart-items-body td {
  padding: 10px;
}
.items-body-information {
  overflow: hidden;
}
.information-left {
  display: table-cell;
  vertical-align: center;
  padding-right: 10px;
}
.information-image {
  display: block;
  max-width: 60px;
  padding: 4px;
  height: auto;
  border: 1px #eee solid;
  border-radius: 4px;
}
.information-body {
  display: table-cell;
  width: 100%;
  vertical-align: middle;
  overflow: hidden;
}
.information-body h5 {
  max-height: 34px;
  line-height: 17px;
  overflow: hidden;
  margin: 0;
}
.number {
  width: 60px;
}
.number-control {
  display: block;
  text-align: center;
}

.body-pull-right {
  display: block;
  text-align: right;
}
.body-pull-right dt {
  display: block;
  width: 1220px;
  line-height: 20px;
  font-weight: normal;
  color: #999999;
  text-align: right;
}
.body-pull-right dd {
  font-weight: normal;
  color: #999999;
  line-height: 20px;
  float: right;
  margin-top: -17px;
}

/* 合计 */
.combined {
  line-height: 48px;
  background-color: #ffffff;
}
.combined-back {
  display: block;
  text-align: center;
  border-right: 1px solid #eeeeee;
}
.combined-sum {
  color: #de342f;
  font-size: 14px;
  font-weight: bold;
}
.combined-btn {
  width: 100%;
  height: 100%;
  color: white;
  opacity: 0.8;
  background: -webkit-linear-gradient(
    left,
    rgb(87, 98, 257),
    rgb(103, 160, 225)
  );
  border: none;
}
.combined-btn:hover {
  opacity: 1;
}
</style>